/**
 * Copyright (c) 2020-2021 浦东大爷 All rights reserved.
 * 机会永远都是留给有准备的人
 */
package com.lagou.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lagou.common.Const;
import com.lagou.common.ResponseCode;
import com.lagou.common.ServerResponse;
import com.lagou.mapper.UserMapper;
import com.lagou.model.User;
import com.lagou.service.IUserService;
import com.lagou.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author: gitwo
 * @date: 2021-03-08
 * @description:
 */
@Service("iUserService")
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ServerResponse<User> login(String username, String password) {
        // 1. 检查用户名是否存在
        int resultCode = userMapper.checkUserName(username);
        if(resultCode == 0){
            return ServerResponse.createByErrorMsg("用户名不存在");
        }
        // 2. 使用MD5给密码进行加密
        String md5EncodeUtf8Password = MD5Util.MD5EncodeUtf8(password);
        // 3. 调用mapper的登录方法，登录成功会返回一个user对象
        User user = userMapper.selectLogin(username, md5EncodeUtf8Password);
        // 4. 如果user对象为null则登录失败，否则登录成功
        if(user == null){
            return ServerResponse.createByErrorMsg("用户名或密码错误");
        }
        user.setPassword(StringUtils.EMPTY);
        // 5. 封装serverResponse，返回成功消息

        return ServerResponse.createBySuccessMsgData("登录成功", user);
    }

    /**
     * 分页查询user
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public ServerResponse<PageInfo> getUser(int pageNum, int pageSize) {
        // 1. 给pageHelper分页助手设置 pageNum pageSize
        PageHelper.startPage(pageNum, pageSize);
        // 2. 查询所有用户信息
        List<User> list = userMapper.userList();
        for (User user : list) {
            user.setPassword(StringUtils.EMPTY);
        }
        // 3. 创建pageInfo对象，把查询到的用户list放到pageInfo中
        PageInfo pageInfo = new PageInfo(list);
        // 4. 返回serverResponse，添加pageInfo
        return ServerResponse.createBySuccessData(pageInfo);
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    @Override
    public ServerResponse<String> add(User user) {
        ServerResponse<String> validResponse = checkValid(user.getUsername(), Const.USERNAME);
        if(validResponse.getStatus() != ResponseCode.SUCCESS.getCode()){
            return validResponse;
        }

        validResponse = checkValid(user.getEmail(), Const.EMAIL);
        if(validResponse.getStatus() != ResponseCode.SUCCESS.getCode()){
            return validResponse;
        }

        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));

        int resultCount = userMapper.insert(user);
        if(resultCount == 0){
            return ServerResponse.createByErrorMsg("用户添加失败");
        }
        return ServerResponse.createBySuccessMsg("添加成功");
    }

    @Override
    public ServerResponse<String> delete(Integer id) {
        int count = userMapper.delete(id);
        if(count > 0){
            return ServerResponse.createBySuccessMsg("删除用户成功");
        } else {
            return ServerResponse.createBySuccessMsg("删除用户ID不存在");
        }
    }


    /**
     * 修改用户
     * @param user
     * @return
     */
    @Override
    public ServerResponse<String> update(User user) {
        ServerResponse<String> validResponse = checkValidForUdate(user);
        if(validResponse.getStatus() != ResponseCode.SUCCESS.getCode()){
            return validResponse;
        }
        int resultCount = userMapper.update(user);
        if(resultCount == 0){
            return ServerResponse.createByErrorMsg("用户更新失败");
        }
        return ServerResponse.createBySuccessMsg("更新成功");
    }

    /**
     * 用户更新的校验逻辑
     * 如果用户名和其他用户名重复则更新失败，但如果是自己原来的可以实现更新
     * 如果邮箱和其他邮箱重复则更新失败，如果是自己现有邮箱，则可以更新
     * @param user
     * @return
     */
    private ServerResponse<String> checkValidForUdate(User user) {
        int iCount = userMapper.checkByUserForUpdate(user);
        if(iCount > 0){
            return ServerResponse.createByErrorMsg("用户名或者邮箱重复");
        }
        return ServerResponse.createBySuccess();
    }

    /**
     * 根据用户ID获取用户信息
     * @param id
     * @return
     */
    @Override
    public ServerResponse<Object> findById(Integer id) {
        User user = userMapper.findById(id);
        if(user == null){
            ServerResponse.createByErrorMsg("用户不存在");
        }
        return ServerResponse.createBySuccessData(user);
    }

    /**
     * 校验是否存在
     * @param str   有可能是用户名或者邮箱
     * @param type  类型可以是用户名也可以是邮箱
     * @return
     */
    public ServerResponse<String> checkValid(String str, String type){
        // 校验用户名
        if(Const.USERNAME.equals(type)){
            //查询用户名是否存在
            int checkUserName = userMapper.checkUserName(str);
            if(checkUserName > 0){
                return ServerResponse.createByErrorMsg("用户名已经存在");
            }
        }
        // 校验邮箱
        if(Const.EMAIL.equals(type)){
           int checkEmail = userMapper.checkEmail(str);
           if(checkEmail > 0){
               return ServerResponse.createByErrorMsg("邮箱已经存在");
           }
        }
        return ServerResponse.createBySuccess();
    }
}
